package com.hqd.utils.pack.complier;

import com.hqd.utils.pack.bean.ProjectInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;

import java.io.File;

/**
 * 编译整个项目
 */
public class AntComelier extends AbstractCompiler {

    public AntComelier(ProjectInfo projectInfo) {
        super(projectInfo);
    }

    @Override
    protected void doCompile() throws Exception {
        Project project = new Project();
        project.setBaseDir(new File(projectInfo.getBasePath()));
        Javac javac = new Javac();
        javac.setProject(project);
        javac.setCompiler(projectInfo.getCompilerClass().getName());
        javac.setClasspath(addLib());
        javac.setSrcdir(new Path(project, projectInfo.getSrcPath()));
        javac.setDestdir(new File(projectInfo.getOutPath()));
        javac.setTarget(projectInfo.getJdkVersion());
        javac.setSource(projectInfo.getJdkVersion());
        javac.setNowarn(projectInfo.isNoWarn());
        javac.setDebug(projectInfo.isDebug());
        javac.setDebugLevel(projectInfo.getDebugLevel());
        javac.setEncoding(projectInfo.getEncoding());
        javac.execute();
        addResources(outPath, new File(projectPath, projectInfo.getResourcePath()).listFiles());
        if (!projectInfo.isSkipTest()) {
            javac.setSrcdir(new Path(project, projectInfo.getTestSrcPath()));
            javac.execute();
            addResources(outPath, new File(projectPath, projectInfo.getTestResourcePath()).listFiles());
        }
    }


    /**
     * 添加依赖
     *
     * @return
     */
    private Path addLib() {
        logger.debug(String.format("\t###### 开始添加依赖 ######"));
        String libPath = projectInfo.getLibPath();
        if (StringUtils.isNotBlank(libPath)) {
            logger.info(String.format("\t\t###### 添加依赖 '%s'  ######", libPath));
            Project project = new Project();
            Path path = new Path(project);
            FileSet fs = new FileSet();
            fs.setDir(new File(libPath));
            fs.setIncludes("**/*.jar");
            path.add(fs);
            return path;
        }
        logger.debug(String.format("\t###### 添加依赖结束 ######"));
        return null;
    }
}
